package cn.inurl.logic;

import java.util.ArrayList;
import java.util.List;

import cn.inurl.bean.Domain;
import cn.inurl.consts.Constants;

public class DomainCheck {
	public List<Domain> getDomainAvailableList(String keyword, String[] suffix){
		if(suffix == null || suffix.length < 1)
			return null;
		List<Domain> domains = new ArrayList<Domain>();
		for (String fix : suffix) {
			Domain domain = parseDomain(getDomainAvailableStatus(keyword, fix));
			if(domain != null)
				domains.add(domain);
		}
		return domains;
	}
	
	public Domain getDomainAvailabel(String yumi){
		String[] status = null;
		StringBuilder queryUrl = new StringBuilder(Constants.CHECK_DOMAIN_URI);
		queryUrl.append(yumi);
		String bodyHtml = HttpClientFactory.execGetMethod(queryUrl.toString());
		if(bodyHtml.startsWith("(\"") && bodyHtml.endsWith("\");")){
			bodyHtml = bodyHtml.substring(2, bodyHtml.length()-3);
			status = bodyHtml.split("\\|");
		}
		return parseDomain(status);
	}
	
	private String[] getDomainAvailableStatus(String keyword, String suffix){
		String[] status = null;
		StringBuilder queryUrl = new StringBuilder(Constants.CHECK_DOMAIN_URI);
		queryUrl.append(keyword).append(suffix);
		String bodyHtml = HttpClientFactory.execGetMethod(queryUrl.toString());
		if(bodyHtml.startsWith("(\"") && bodyHtml.endsWith("\");")){
			bodyHtml = bodyHtml.substring(2, bodyHtml.length()-3);
			status = bodyHtml.split("\\|");
		}
		return status;
	}
	
	private Domain parseDomain(String[] status){
		if(status == null || status.length != 4)
			return null;
		Domain domain = new Domain();
		domain.setSuffix(status[0]);
		domain.setDomain(status[1]);
		domain.setStatus(Integer.parseInt(status[2]));
		domain.setDescpt(status[3]);
		return domain;
	}
}
